package com.supersit.greensproject.activity;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import com.supersit.greensproject.DB.XUtilsDbManager;
import com.supersit.greensproject.R;
import com.supersit.greensproject.adapter.PriceGatherBaseSelectAutoTvAdapter;
import com.supersit.greensproject.adapter.PriceGatherMaketSelectAutoTvAdapter;
import com.supersit.greensproject.entity.MaketSubject;
import com.supersit.greensproject.entity.PriceGather;
import com.supersit.greensproject.utils.T;
import com.supersit.greensproject.view.MyTitleBar;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

/**
 * Created by chen on 2016/7/25.
 */
@ContentView(R.layout.activity_price_gather_edit)
public class PriceGatherEditActivity extends BaseActivity {
    private Context context;
    private MyTitleBar myTitleBar;
    @ViewInject(R.id.sp_area)
    private Spinner spMaketArea;
    @ViewInject(R.id.sp_maket_type)
    private Spinner spMaketType;
    @ViewInject(R.id.sp_merchandise)
    private Spinner spMerchandise;//类型 五大类
    @ViewInject(R.id.sp_detection_result)
    private Spinner spDetectionresult;//检测结果
    @ViewInject(R.id.et_business_licence)
    private EditText etBusinessLicence;//营业执照
    @ViewInject(R.id.et_maket_name)
    private AutoCompleteTextView actMakteName;
    @ViewInject(R.id.et_market_address)
    private EditText etMaketAddress;
    @ViewInject(R.id.et_contacts)
    private EditText etContacts;
    @ViewInject(R.id.et_tel)
    private EditText etTel;
    @ViewInject(R.id.et_product_name)
    private EditText etProductName;//产品名称
    @ViewInject(R.id.et_from_base)
    private AutoCompleteTextView etFromBase;
    @ViewInject(R.id.et_average_price)
    private EditText etPrice;
    @ViewInject(R.id.et_number_of_transactions)
    private EditText etTransactionsNum;//交易数量
    @ViewInject(R.id.et_create_date)
    private EditText etCreateDate;
    @ViewInject(R.id.btn_save_data)
    private Button btnSaveData;
    private DbManager db;
    private PriceGather pg;
    private String[] columns = new String[]{"maketName", "id", "id as _id"};
    private PriceGatherMaketSelectAutoTvAdapter priceGatherAutoTvAdapter;
    String[] baseColumns = new String[]{"baseName", "id", "id as _id"};
    private PriceGatherBaseSelectAutoTvAdapter autoTvAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        context = this;
        setTitleBar();
        initVariable();
        bindListener();
    }

    private void setTitleBar() {
        myTitleBar = new MyTitleBar(context, findViewById(R.id.price_gather_edit_title));
        myTitleBar.setTitleText(getResources().getString(R.string.price_gather));
        myTitleBar.setChildVisibility(false, myTitleBar.getmImgRight());
    }

    private void bindListener() {
        myTitleBar.setImg1Listener(onClickListener);
        btnSaveData.setOnClickListener(onClickListener);
        actMakteName.setOnItemClickListener(onItemClickListener);
        actMakteName.addTextChangedListener(textWatcher);
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.title_bar_left:
                    finish();
                    break;
                case R.id.btn_save_data:
                    saveData();
                    break;
            }
        }
    };

    private void initVariable() {
        db = db = XUtilsDbManager.getInstance();
        ArrayAdapter maketAreaAdapter = ArrayAdapter.createFromResource(
                context, R.array.area, R.layout.spinner_text);
        maketAreaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spMaketArea.setAdapter(maketAreaAdapter);
        ArrayAdapter maketTypeAdapter = ArrayAdapter.createFromResource(
                context, R.array.maket_type, R.layout.spinner_text);
        maketTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spMaketType.setAdapter(maketTypeAdapter);
        ArrayAdapter merchandiseAdapter = ArrayAdapter.createFromResource(
                context, R.array.merchandise, R.layout.spinner_text);
        merchandiseAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spMerchandise.setAdapter(merchandiseAdapter);
        ArrayAdapter detectionResultAdapter = ArrayAdapter.createFromResource(
                context, R.array.detection_result, R.layout.spinner_text);
        detectionResultAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spDetectionresult.setAdapter(detectionResultAdapter);
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            pg = (PriceGather) bundle.getSerializable("pricegather");
            String[] areas = getResources().getStringArray(R.array.area);
            String[] maketTypes = getResources().getStringArray(R.array.maket_type);
            String[] merchandises = getResources().getStringArray(R.array.merchandise);//作为种类 五大类
            String[] ecification = getResources().getStringArray(R.array.specifications);//规格
            String[] detectionResults = getResources().getStringArray(R.array.detection_result);//检测结果

            for (int i = 0; i < areas.length; i++) {
                if (pg.getMaketArea() != null) {
                    if (areas[i].equals(pg.getMaketArea())) {
                        spMaketArea.setSelection(i);
                    }
                }
            }
            spMaketType.setSelection(pg.getMaketType() == 0 ? 0 : pg.getMaketType());
            spMerchandise.setSelection(pg.getMerchandise() == 0 ? 0 : pg.getMerchandise());//类型 五大类
            spDetectionresult.setSelection(pg.getDetectionResult() == 0 ? 0 : pg.getDetectionResult());//检测结果
            etBusinessLicence.setText(pg.getBusinessLicence() == null ? "" : pg.getBusinessLicence());//营业执照
            actMakteName.setText(pg.getMaketName() == null ? "" : pg.getMaketName());
            etMaketAddress.setText(pg.getMaketAddress() == null ? "" : pg.getMaketAddress());
            etContacts.setText(pg.getContacts() == null ? "" : pg.getContacts());
            etTel.setText(pg.getTel() == null ? "" : pg.getTel());
            etProductName.setText(pg.getProductName() == null ? "" : pg.getProductName());//产品名称
            etFromBase.setText(pg.getFromBase() == null ? "" : pg.getFromBase());
            etPrice.setText(pg.getAveragePrice() == null ? "" : pg.getAveragePrice());
            etTransactionsNum.setText(pg.getTransactionsNum() == null ? "" : pg.getTransactionsNum());//交易数量
            etCreateDate.setText(pg.getCreateDate() == null ? "" : pg.getCreateDate());
            spMaketArea.setEnabled(false);
            spMaketArea.setClickable(false);
            spMaketType.setEnabled(false);
            spMaketType.setClickable(false);
            /**设置字符数*/
            actMakteName.setThreshold(1);
            priceGatherAutoTvAdapter = new PriceGatherMaketSelectAutoTvAdapter(context, null, 0, columns);
            actMakteName.setAdapter(priceGatherAutoTvAdapter);
            actMakteName.setThreshold(1);
            autoTvAdapter = new PriceGatherBaseSelectAutoTvAdapter(context, null, 0, baseColumns);
            etFromBase.setAdapter(autoTvAdapter);
        }
    }

    private void saveData() {
        String businessLicence;
        String maketName;
        String maketAddress;
        String contacts;
        String tel;
        String area;
        int maketType;
        String productName;
        int merchandises;//类型 五大类
        String fromBase;
        int detectionResult;//检测结果
        int ecification;//规格
        String price;
        String transactionsNum;
        String createDate;
        businessLicence = etBusinessLicence.getText() == null ? "" : etBusinessLicence.getText().toString();
        maketAddress = etMaketAddress.getText() == null ? "" : etMaketAddress.getText().toString();
        maketName = actMakteName.getText() == null ? "" : actMakteName.getText().toString();
        contacts = etContacts.getText() == null ? "" : etContacts.getText().toString();
        tel = etTel.getText() == null ? "" : etTel.getText().toString();
        String[] areas = getResources().getStringArray(R.array.area);
        area = areas[spMaketArea.getSelectedItemPosition()];
        maketType = spMaketType.getSelectedItemPosition();
        productName = etProductName.getText() == null ? "" : etProductName.getText().toString();
        merchandises = spMerchandise.getSelectedItemPosition();
        fromBase = etFromBase.getText() == null ? "" : etFromBase.getText().toString();
        detectionResult = spDetectionresult.getSelectedItemPosition();
        price = etPrice.getText() == null ? "" : etPrice.getText().toString();
        transactionsNum = etTransactionsNum.getText() == null ? "" : etTransactionsNum.getText().toString();
        createDate = etCreateDate.getText() == null ? "" : etCreateDate.getText().toString();
        pg.setBusinessLicence(businessLicence);
        pg.setMaketName(maketName);
        pg.setMaketAddress(maketAddress);
        pg.setContacts(contacts);
        pg.setTel(tel);
        pg.setMaketArea(area);
        pg.setMaketType(maketType);
        pg.setProductName(productName);
        pg.setMerchandise(merchandises);
        pg.setFromBase(fromBase);
        pg.setDetectionResult(detectionResult);
        pg.setAveragePrice(price);
        pg.setTransactionsNum(transactionsNum);
        pg.setCreateDate(createDate);
        pg.setOperationsTatus(2);
        try {
            db.update(pg);
        } catch (DbException e) {
            e.printStackTrace();
        }
        T.showShort(context, R.string.save_ok);
        finish();
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
         resettingViewPortion();
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    };
    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            int mid = (int) view.getTag();
            try {
                MaketSubject ms = db.selector(MaketSubject.class).where("id", "=", mid).findFirst();
                if (null != ms) {
                    // T.showShort(context, ms.getBusinessLicence());
                    actMakteName.setText(ms.getMaketName() == null ? "" : ms.getMaketName());
                    etBusinessLicence.setText(ms.getBusinessLicence());//营业执照
                    etMaketAddress.setText(ms.getMaketAddress() == null ? "" : ms.getMaketAddress());
                    etContacts.setText(ms.getOperator() == null ? "" : ms.getOperator());
                    etTel.setText(ms.getTel() == null ? "" : ms.getTel());
                    spMaketArea.setSelection(ms.getAreaId());
                    spMaketType.setSelection(ms.getCategory());

                }

            } catch (DbException e) {
                e.printStackTrace();
            }
        }
    };

    private void resettingViewPortion() {

        spMaketArea.setSelection(0);

        spMaketType.setSelection(0);

        spMerchandise.setSelection(0);//类型 五大类

        spDetectionresult.setSelection(0);//检测结果

        //etMakteName.setText("");

        etBusinessLicence.setText("");//营业执照
        etMaketAddress.setText("");

        etContacts.setText("");

        etTel.setText("");

//        etProductName.setText("");//产品名称
//
//        etFromBase.setText("");
//
//        etPrice.setText("");
//
//        etTransactionsNum.setText("");//交易数量
//
//        etCreateDate.setText("");
    }
}
